import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Resource } from '@modelcontextprotocol/sdk/types';
import { Logger } from '~/utils/logger';

export interface DesignResource extends Resource {
  uri: string;

  name: string;

  description: string;

  mimeType: string;

  /** blob 的 Base64 编码 */
  blob?: string;

  text?: string; // 可选的文本内容
}

export const transientResourceStore = new Map<string, DesignResource>(); // Key: resource.uri

export const resourceUriPrefix = 'idoc://'; // Prefix for transient resources

export const designResourceTemplate = new ResourceTemplate(
  `${resourceUriPrefix}{appId}-{designId}`,
  {
    list: function () {
      const keys = transientResourceStore.keys();

      const resources = Array.from(keys)
        .map(key => {
          const resource = transientResourceStore.get(key);
          if (resource) {
            return {
              uri: resource.uri,
              mimeType: resource.mimeType,
              name: resource.name,
              description: resource.description,
            };
          }
          return null;
        })
        .filter(Boolean) as Array<{
        uri: string;
        mimeType: string;
        name?: string;
        description?: string;
      }>;

      Logger.info(`[ResourceTemplate] 返回 ${resources.length} 个资源`);
      return {
        resources,
      };
    },
  }
);

export function getResourceByUri(uri: string): DesignResource {
  return transientResourceStore.get(uri);
}
